package parser

import (
	"engine"
	"log"
	"path"
	"regexp"
	model "smarthome-model"
)

var (
	ResourceFileReg = regexp.MustCompile(`<a href="([0-9a-zA-Z].+\.[a-z].+)">([^<]*)</a>`)
)

const ProductResourceFile = "ProductResourceFile"

func ParseResource(content []byte, url, prodId, basePath string) engine.ParserResult {
	resourceFiles := ResourceFileReg.FindAllStringSubmatch(string(content), -1)
	resourceDirs := ResourceDir.FindAllStringSubmatch(string(content), -1)
	result := engine.ParserResult{}
	result = addResourceResult(resourceFiles, ProductResourceFile, url, prodId, basePath, result)
	result = addResourceResult(resourceDirs, ProductResourceDir, url, prodId, basePath, result)
	return result
}

func addResourceResult(resultSet [][]string, resultType, url, prodId, basePath string, pResult engine.ParserResult) engine.ParserResult {
	for _, results := range resultSet {
		result := results[1]
		item := model.ProdParseItem{
			Url:       url + result,
			ProdId:    prodId,
			ParseType: resultType,
		}
		switch resultType {
		case ProductResourceFile:
			item.FilePath = path.Join(basePath, result)
			item.IsDir = false
		case ProductResourceDir:
			item.FilePath = path.Join(basePath, result)
			request := engine.Request{
				CurURL: url + result,
				RefURL: url,
				ParserFunc: func(c []byte) engine.ParserResult {
					return ParseResource(c, url+result, prodId, item.FilePath)
				},
			}
			pResult.Requests = append(pResult.Requests, request)
			item.IsDir = true
		default:
			log.Println("addResult: unknown result type!")
			continue
		}
		pResult.Items = append(pResult.Items, item)

	}
	return pResult
}
